package com.javaee.ch11.web;

import com.javaee.ch11.common.response.ResultVo;
import com.javaee.ch11.entity.Book;
import com.javaee.ch11.entity.BookCategory;
import com.javaee.ch11.service.BookCategoryService;
import com.javaee.ch11.web.dto.BookCategoryQueryDto;
import com.javaee.ch11.web.dto.BookQueryDto;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Validated
@RestController
@RequestMapping("/api/bookCategory")
public class BookCategoryController {

    @Autowired
    private BookCategoryService bookCategoryService;

    @PostMapping("/query")
    public ResultVo<List<BookCategory>> query(@RequestBody BookCategoryQueryDto queryDto) {
        return ResultVo.ok(bookCategoryService.queryBooks(queryDto));
    }

    /**
     * 获取指定ID的书籍分类信息。
     *
     * @param id 书籍分类ID
     * @return 包含书籍分类对象的ResultVo
     */
    @GetMapping("/{id}")
    public ResultVo<BookCategory> get(@PathVariable long id) {
        BookCategory bookCategory = bookCategoryService.getById(id);
        return ResultVo.ok(bookCategory);
    }

    /**
     * 添加新书籍分类。
     *
     * @param bookCategory 新书籍分类对象
     * @return 操作结果的ResultVo
     */
    @PostMapping("/")
    public ResultVo add(@Valid @RequestBody BookCategory bookCategory) {
        bookCategoryService.add(bookCategory);
        return ResultVo.ok();
    }

    /**
     * 更新书籍分类信息。
     *
     * @param bookCategory 要更新的书籍分类对象
     * @return 操作结果的ResultVo
     */
    @PutMapping("/")
    public ResultVo update(@Valid @RequestBody BookCategory bookCategory) {
        bookCategory.setUpdatedTime(new Date());
        bookCategoryService.updateById(bookCategory);
        return ResultVo.ok();
    }

    /**
     * 删除指定ID的书籍分类。
     *
     * @param id 书籍分类ID，不能小于0
     * @return 操作结果的ResultVo
     */
    @DeleteMapping("/{id}")
    public ResultVo delete(@PathVariable @Min(value = 0, message = "不能小于0") long id) {
        bookCategoryService.deleteById(id);
        return ResultVo.ok();
    }

    /**
     * 获取所有书籍分类列表。
     *
     * @return 包含书籍分类列表的ResultVo
     */
    @GetMapping("/")
    public ResultVo<List<BookCategory>> list() {
        return ResultVo.ok(bookCategoryService.listAll());
    }
}